package cn.fl.custpay.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.custpay.condition.CmmCstProposalQueryCondition;
import cn.fl.custpay.service.ICmmCstProposalService;
import cn.fl.custpay.vo.CmmCstProposalVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;
import fl.constant.facade.framework.constant.TableConstant;
import fl.constant.facade.framework.constant.UploadConstant;

/**
 * @Description: 用户建议反馈表 控制层
 */
@Controller
@RequestMapping("/custpay/cmmCstProposal")
public class CmmCstProposalController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmmCstProposalController.class);

	/**
	 * CmmCstProposal 服务层BEAN
	 */
	@Autowired
	private ICmmCstProposalService cmmCstProposalService;

	/**
	 * 文件 服务层BEAN
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;

	@Autowired
	private ISysUsrApiService sysUsrApiService;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toCmmCstProposalListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("custpay/cmmCstProposal/cmmCstProposalList");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("custpay/cmmCstProposal/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initCmmCstProposalList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String clientPhone = request.getParameter("clientPhone");
		String clientName = request.getParameter("clientName");
		String content = request.getParameter("content");
		String prpslSts = request.getParameter("prpslSts");
		String crtTmBegin = request.getParameter("crtTmBegin");
		String crtTmEnd = request.getParameter("crtTmEnd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CmmCstProposalQueryCondition qc = new CmmCstProposalQueryCondition();
		if (StringUtils.isNotEmpty(clientPhone)) {
			qc.setClientPhone(clientPhone);
		}
		if (StringUtils.isNotEmpty(clientName)) {
			qc.setClientName(clientName);
		}
		if (StringUtils.isNotEmpty(content)) {
			qc.setContent(content);
		}
		if(StringUtils.isNotEmpty(prpslSts)){
			qc.setPrpslSts(Long.valueOf(prpslSts));
		}
		if (StringUtils.isNotEmpty(crtTmBegin)) {
			qc.setCrtTmBegin(DateUtils.formatStringToDate(crtTmBegin,DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(crtTmEnd)) {
			qc.setCrtTmEnd(DateUtils.formatStringToDate(crtTmEnd, DateUtils.YYYY_MM_DD));
		}
		page.setCondition(qc);
		
		//TODO SOMETHING
		Pager pager = this.cmmCstProposalService.searchListPage(page);
		List<CmmCstProposalVO> list = (List<CmmCstProposalVO>)pager.getResultList();
		Map<String,String> oscdmap = this.cmmCstProposalService.searchGroupToMap(CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd(), DictionaryConstant.CODE_OP_TYP_CD);
		Map<String,String> prpslstsmap = new HashMap<String,String>();
		prpslstsmap.put("0","未处理");
		prpslstsmap.put("1","已处理");
		for(CmmCstProposalVO _vo : list){
			if(StringUtils.isNotEmpty(_vo.getOsCd())){
				_vo.setOsCdNm(oscdmap.get(String.valueOf(_vo.getOsCd())));
			}
			if(StringUtils.isNotEmpty(_vo.getPrpslSts())){
				_vo.setPrpslStsNm(prpslstsmap.get(String.valueOf(_vo.getPrpslSts())));
			}
			if(StringUtils.isNotEmpty(_vo.getMdfUsrId())){
				SysUsrDTO sysUsrDTO = this.sysUsrApiService.selectSysUsrById(_vo.getMdfUsrId(),CurrentThreadContext.getFlServiceSysCd(),CurrentThreadContext.getCurrentOrgCd());
				if(null != sysUsrDTO && StringUtils.isNotEmpty(sysUsrDTO.getRefRlNm())){
					_vo.setMdfUsrNm(sysUsrDTO.getRefRlNm());
				}
			}
		}
		ListPageVO<CmmCstProposalVO> listPage = new ListPageVO<CmmCstProposalVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.cmmCstProposalService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 删除多条数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeById", "删除数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.parseArray(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		try {
			boolean success = this.cmmCstProposalService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeById", "删除数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+ids+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	@RequestMapping(value = "/seeCmmCstProposalPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView seeCmmCstProposalPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("custpay/cmmCstProposal/seeCmmCstProposal");
		CmmCstProposalVO entity = new CmmCstProposalVO();
		List<SysUlFilesRecVO> fileList = new ArrayList<SysUlFilesRecVO>();
		if(StringUtils.isNotEmpty(id)){
			entity = this.cmmCstProposalService.selectById(Long.valueOf(id));
			SysUlFilesRecQueryCondition ulFileQc = new SysUlFilesRecQueryCondition();
			ulFileQc.setCfgCd(PropertiesCacheUtils.getProperty(UploadConstant.CFG_CST_PROPOSAL_CD));
			ulFileQc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
			ulFileQc.setOrgCd(PropertiesCacheUtils.getProperty(UploadConstant.CFG_CST_PROPOSAL_ORG_CD));
			ulFileQc.setPkId(id);
			ulFileQc.setTabNm(PropertiesCacheUtils.getProperty(TableConstant.CMM_CST_PROPOSAL));
			ulFileQc.setCfgDtlCd(PropertiesCacheUtils.getProperty(UploadConstant.CFG_DTL_CST_PROPOSAL_CD));
			fileList = sysUlFilesRecService.searchList(ulFileQc);
		}
		String serverPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);//服务地址
		String customerPah = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_COSTOMER_PATH);
		String headPic = PropertiesCacheUtils.getProperty(UploadConstant.DEFAULT_NO_PIC);
		view.addObject("defImg", serverPath+customerPah+headPic);
		view.addObject("fileList",fileList);
		view.addObject("cmmcstproposal",entity);
		BaseLogUtils.info(logger, "seeCmmCstProposalPage", "跳转到查看页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 处理页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/modifyCmmCstProposalPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView modifyCmmCstProposalPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("custpay/cmmCstProposal/modifyCmmCstProposal");
		CmmCstProposalVO entity = new CmmCstProposalVO();
		List<SysUlFilesRecVO> fileList = new ArrayList<SysUlFilesRecVO>();
		if(StringUtils.isNotEmpty(id)){
			entity = this.cmmCstProposalService.selectById(Long.valueOf(id));
			SysUlFilesRecQueryCondition ulFileQc = new SysUlFilesRecQueryCondition();
			ulFileQc.setCfgCd(PropertiesCacheUtils.getProperty(UploadConstant.CFG_CST_PROPOSAL_CD));
			ulFileQc.setSysCd(CurrentThreadContext.getFlServiceSysCd());
			ulFileQc.setOrgCd(PropertiesCacheUtils.getProperty(UploadConstant.CFG_CST_PROPOSAL_ORG_CD));
			ulFileQc.setPkId(id);
			ulFileQc.setTabNm(PropertiesCacheUtils.getProperty(TableConstant.CMM_CST_PROPOSAL));
			ulFileQc.setCfgDtlCd(PropertiesCacheUtils.getProperty(UploadConstant.CFG_DTL_CST_PROPOSAL_CD));
			fileList = sysUlFilesRecService.searchList(ulFileQc);
		}
		String serverPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);//服务地址
		String customerPah = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_COSTOMER_PATH);
		String headPic = PropertiesCacheUtils.getProperty(UploadConstant.DEFAULT_NO_PIC);
		view.addObject("defImg", serverPath+customerPah+headPic);
		view.addObject("fileList",fileList);
		view.addObject("cmmcstproposal",entity);
		BaseLogUtils.info(logger, "modifyCmmCstProposalPage", "跳转到查看页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CmmCstProposalVO vo = this.cmmCstProposalService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CmmCstProposalVO entity = null;
		try {
			entity = new CmmCstProposalVO();
			//TODO ADD PARAM
			Long id = this.cmmCstProposalService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String cmmcstproposalId = request.getParameter("cmmcstproposalId");
		String prpslSts = request.getParameter("prpslSts");
		String finResult = request.getParameter("finResult");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "保存成功");
		if(StringUtils.isEmpty(cmmcstproposalId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+cmmcstproposalId+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		CmmCstProposalVO entity = null;
		try {
			entity = new CmmCstProposalVO();
			entity.setId(Long.valueOf(cmmcstproposalId));
			if(StringUtils.isNotEmpty(prpslSts)){
				entity.setPrpslSts(Long.valueOf(prpslSts));
			}
			if(StringUtils.isNotEmpty(finResult)){
				entity.setFinResult(finResult);
			}
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			entity.setMdfTm(new Date());
			//TODO ADD PARAM
			boolean success = this.cmmCstProposalService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("保存失败");
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+cmmcstproposalId+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+cmmcstproposalId+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+cmmcstproposalId+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+cmmcstproposalId+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

